﻿using Microsoft.Practices.Unity;

namespace MvvmFx.Common.ViewModels.Behaviors.LoadingSaving
{
    /// <summary>
    /// Abstract base class for a XxxSaver.
    /// This object saves the state of a ViewModel to the business objects in the model.
    /// </summary>
    public abstract class ViewModelSaver<T> : IViewModelSaver<T> where T : ILoadSaveable
    {
        protected ViewModelSaver(IUnityContainer container)
        {
            this.Container = container;
        }

        #region properties

        /// <summary>
        /// Dependency container to be used for DI by child classes.
        /// </summary>
        protected IUnityContainer Container
        {
            get;
            private set;
        }

        #endregion

        /// <summary>
        /// Saves the state of the ViewModel back to the corresponding bussiness objects
        /// in the model.
        /// </summary>
        /// <param name="vm"></param>
        public void Save(T vm)
        {
            // Save the page data to the state object, if it's been modified
            //
            if (vm.ChangeService.IsModified)
            {
                // Save the page
                OnSave(vm);

                // Mark the view model as being UnModified
                //
                vm.ChangeService.MarkUnmodified();
            }
        }

        public void Save(ILoadSaveable vm)
        {
            Save((T)vm);
        }

        /// <summary>
        /// Override in derived classes to save the data in the ViewModel back to the model.
        /// </summary>
        /// <param name="vm"></param>
        protected abstract void OnSave(T vm);
    }
}